package com.purchase.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.StringUtils;

/**
 * Module ID: </br>
 * Comments：本类为工具通用类</br>
 */
public class Utils {
	
	/**
	 * @Title: JudgePhoneNumber   
	 * @Description: 验证手机号正确性  
	 * @author: JiangShuai
	 * @param: @param phoneNumber
	 * @param: @return      
	 * @return: Boolean
	 */
	public static Boolean JudgePhoneNumber(String phoneNumber) {
		if(!StringUtils.hasText(phoneNumber)) {
			return false;
		}
		String regex ="^1[3|4|5|6|7|8|9][0-9]\\d{4,8}$";
        if(phoneNumber.length() != 11){
            System.out.println("手机号应为11位数");
        }else{
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phoneNumber);
            boolean isMatch = m.matches();
            if(isMatch){
            	return true;
                //System.out.println("您的手机号" + phone + "是正确格式@——@");
            }
        }
		return false;
	}
	
	/**
	 * @Title: JudgeFileType   
	 * @Description: 根据后缀名判断是那种类型的文件  
	 * @author: JiangShuai 
	 * @param: @param suffix  后缀名
	 * @param: @return      
	 * @return: int 1为图片 2为视频
	 */
	public static int JudgeFileType(String suffix) {
		int in = 0;
		if(StringUtils.hasText(suffix)) {
	        switch(suffix){
	        	//图片
	            case "jpg":in=1;
	                break;
	            case "JPG":in=1;
                	break;
	            case "jpeg":in=1;
                	break;
	            case "JPEG":in=1;
                	break;
	            case "png":in=1;
	                break;
	            case "PNG":in=1;
	            	break;
	            case "gif":in=1;
	                break;
	            case "GIF":in=1;
	            	break;
	            //视频
	            case "avi":in=2;
            		break;
	            case "AVI":in=2;
        			break;
	            case "rm":in=2;
	        		break;
	            case "RM":in=2;
	    			break;
	            case "mp4":in=2;
		    		break;
		        case "MP4":in=2;
					break;
	            case "flv":in=2;
		    		break;
		        case "FLV":in=2;
					break;
	            case "wma":in=2;
		    		break;
		        case "WMA":in=2;
					break;
	            case "rmvb":in=2;
		    		break;
		        case "RMVB":in=2;
					break;
	            case "flash":in=2;
		    		break;
		        case "FLASH":in=2;
					break;
	            case "mid":in=2;
		    		break;
		        case "MID":in=2;
					break;
	            case "3gp":in=2;
		    		break;
		        case "3GP":in=2;
					break;
	        }
		}
		return in;
	}
	
	public static String getDateString() {
	     SimpleDateFormat sf = new SimpleDateFormat("yyyyMM");
	     SimpleDateFormat dd=new SimpleDateFormat("dd");
	     String yearMonth=sf.format(new Date());
	     String day=dd.format(new Date());
	     return yearMonth+"/"+day+"/";
	}

	/**
	 * @Title: isInt   
	 * @Description: 判断Str是不是数字 
	 * @author: JiangShuai
	 * @param: @param str
	 * @param: @return      
	 * @return: boolean
	 */
	public static boolean isInt(String str) {
		Pattern pattern = Pattern.compile("(0|[1-9][0-9]*)");
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}

	/**
	 * @Title: subBefore   
	 * @Description: 截取src中term之前的子字符串 
	 * @author: JiangShuai
	 * @param: @param src	父级字符串
	 * @param: @param term  子字符串
	 * @param: @return      
	 * @return: String
	 */
	public static String subBefore(String src, String term) {
		if (src == null || term == null) {
			return null;
		} else {
			int index = src.indexOf(term);
			return index >= 0 ? src.substring(0, index) : src;
		}
	}

	/**
	 * @Title: subAfter   
	 * @Description:   截取src中term之后的子字符串 
	 * @author: JiangShuai
	 * @param: @param src 父级字符串
	 * @param: @param term 子字符串
	 * @param: @return      
	 * @return: String
	 */
	public static String subAfter(String src, String term) {
		if (src == null || term == null) {
			return null;
		} else {
			int index = src.indexOf(term);
			return index >= 0 ? src.substring(index + term.length()) : src;
		}
	}

	/**
	 * get substring last before term from src
	 * 
	 * @param src
	 * @param term
	 * @return string
	 */
	public static String subLastBefore(String src, String term) {
		if (src == null || term == null) {
			return null;
		} else {
			int index = src.lastIndexOf(term);
			return index >= 0 ? src.substring(0, index) : src;
		}
	}

	/**
	 * trim String
	 * 
	 * @param str
	 * @return String
	 */
	public static String trimStr(String str) {
		if (null != str)
			return str.trim();
		else
			return str;
	}
	
	/**
	 * @param str
	 * @param charset
	 * @return String
	 */
	public static String encodeStr(String str, String charset) {
		if (isNull(str)) {
			return str;
		} else {
			try {
				return new String(str.getBytes(charset));
			} catch (Exception e) {
				return str;
			}
		}
	}
	
	/**
	 * check String is null or not;
	 * 
	 * @param checkStr
	 * @return boolean
	 */
	public static boolean isNull(String checkStr) {
		return checkStr == null || checkStr.trim().length() == 0
				|| checkStr.trim().equalsIgnoreCase("null");
	}
	
	/**
	 * get substring last after term from src
	 * 
	 * @param src
	 * @param term
	 * @return string
	 */
	public static String subLastAfter(String src, String term) {
		if (src == null || term == null) {
			return null;
		} else {
			int index = src.lastIndexOf(term);
			return index >= 0 ? src.substring(index + term.length()) : src;
		}
	}

	/**
	 * 获取字符串区间
	 * @param str
	 * @param start
	 * @param end
	 * @return
	 */
	public static String substring(String str, int start) {
		if (str == null) {
			return null;
		}

		// handle negatives, which means last n characters
		if (start < 0) {
			start = str.length() + start; // remember start is negative
		}

		if (start < 0) {
			start = 0;
		}
		if (start > str.length()) {
			return "";
		}

		return str.substring(start);
	}

	/**
	 * 获取字符串区间
	 * @param str
	 * @param start
	 * @param end
	 * @return
	 */
	public static String substring(String str, int start, int end) {
		if (str == null) {
			return null;
		}

		// handle negatives
		if (end < 0) {
			end = str.length() + end; // remember end is negative
		}
		if (start < 0) {
			start = str.length() + start; // remember start is negative
		}

		// check length next
		if (end > str.length()) {
			end = str.length();
		}

		// if start is greater than end, return ""
		if (start > end) {
			return "";
		}

		if (start < 0) {
			start = 0;
		}
		if (end < 0) {
			end = 0;
		}

		return str.substring(start, end);
	}

	// Left/Right/Mid
	// -----------------------------------------------------------------------
	/**
	 * <p>
	 * Gets the leftmost <code>len</code> characters of a String.
	 * </p>
	 * 
	 * <p>
	 * If <code>len</code> characters are not available, or the String is
	 * <code>null</code>, the String will be returned without an exception. An
	 * exception is thrown if len is negative.
	 * </p>
	 * 
	 * <pre>
	 * StringUtils.left(null, *)    = null
	 * StringUtils.left(*, -ve)     = ""
	 * StringUtils.left("", *)      = ""
	 * StringUtils.left("abc", 0)   = ""
	 * StringUtils.left("abc", 2)   = "ab"
	 * StringUtils.left("abc", 4)   = "abc"
	 * </pre>
	 * 
	 * @param str the String to get the leftmost characters from, may be null
	 * @param len the length of the required String, must be zero or positive
	 * @return the leftmost characters, <code>null</code> if null String input
	 */
	public static String left(String str, int len) {
		if (str == null) {
			return null;
		}
		if (len < 0) {
			return "";
		}
		if (str.length() <= len) {
			return str;
		} else {
			return str.substring(0, len);
		}
	}

	/**
	 * <p>
	 * Gets the rightmost <code>len</code> characters of a String.
	 * </p>
	 * 
	 * <p>
	 * If <code>len</code> characters are not available, or the String is
	 * <code>null</code>, the String will be returned without an an exception.
	 * An exception is thrown if len is negative.
	 * </p>
	 * 
	 * <pre>
	 * StringUtils.right(null, *)    = null
	 * StringUtils.right(*, -ve)     = ""
	 * StringUtils.right("", *)      = ""
	 * StringUtils.right("abc", 0)   = ""
	 * StringUtils.right("abc", 2)   = "bc"
	 * StringUtils.right("abc", 4)   = "abc"
	 * </pre>
	 * 
	 * @param str the String to get the rightmost characters from, may be null
	 * @param len the length of the required String, must be zero or positive
	 * @return the rightmost characters, <code>null</code> if null String input
	 */
	public static String right(String str, int len) {
		if (str == null) {
			return null;
		}
		if (len < 0) {
			return "";
		}
		if (str.length() <= len) {
			return str;
		} else {
			return str.substring(str.length() - len);
		}
	}

	/**
	 * check term is exist from src
	 * 
	 * @param src
	 * @param term
	 * @return boolean
	 */
	public static boolean exist(String src, String term) {
		if (src == null || term == null) {
			return false;
		}
		int index = src.indexOf(term);
		return index >= 0;
	}

	/**
	 * encode url
	 * 
	 * @param src
	 * @return String
	 */
	public static String encodeURL(String src) {
		String result = null;
		try {
			result = URLEncoder.encode(src, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * decode url
	 * 
	 * @param src
	 * @return String
	 * @throws UnsupportedEncodingException
	 */
	public static String decodeURL(String src) throws UnsupportedEncodingException {
		return URLDecoder.decode(src, "UTF-8");
	}

	/**
	 * 
	 * @return String
	 */
	public static String format() {
		return format("yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 
	 * @param pattern
	 * @return string
	 */
	public static String format(String pattern) {
		return format(pattern, new Date());
	}

	/**
	 * 
	 * @param pattern
	 * @param date
	 * @return string
	 */
	public static String format(String pattern, Date date) {
		return new SimpleDateFormat(pattern).format(date);
	}

	/**
	 * 
	 * @param pattern
	 * @param text
	 * @return Date
	 */
	public static Date parse(String pattern, String text) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		try {
			return dateFormat.parse(text);
		} catch (ParseException ex) {
			return new Date();
		}
	}

	/**
	 * 
	 * @param str
	 * @param rex
	 * @return boolean
	 */
	public static boolean rexp(String str, String rex) {
		Pattern pattern = Pattern.compile(rex);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}

	/**
	 * 生成UUID
	 * 
	 * @return String
	 * */
    public static String getUUID() {  
        return UUID.randomUUID().toString().replace("-", "");  
    }  
	
	/**
	 * 生成多个UUID
	 * 
	 * @param count
	 *            数量
	 * 
	 * @return String[]
	 * */
	public static String[] getUUID(int count) {
		if (count < 1)
			return null;
		String[] uuid = new String[count];
		for (int i = 0; i < count; i++)
			uuid[i] = getUUID();
		return uuid;
	}

	/**
	 * 获得当前年份
	 * 
	 * @return int
	 */
	public static int getNowYear() {
		Calendar now = Calendar.getInstance();
		return now.get(Calendar.YEAR);
	}

	/**
	 * 获取随机数
	 * 
	 * @param length
	 *            长度
	 * 
	 * @return String
	 */
	public static String getRandomNum(int length) {
		Random rd = new Random(); // 创建随机对象
		String n = "";
		int rdGet; // 取得随机数
		do {
			rdGet = Math.abs(rd.nextInt()) % 10 + 48; // 产生48到57的随机数(0-9的键位值)
			char num1 = (char) rdGet;
			String dd = Character.toString(num1);
			n += dd;

		} while (n.length() < length);// 假如长度小于4
		return n;
	}


	/**
	 * 格式化时间，按照yyyy-MM-dd HH:mm:ss格式
	 * 
	 * @param date
	 *            时间
	 * 
	 * @return String
	 */
	public static String formatDate(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(date);
	}

	/**
	 * 格式化时间，按照yyyy-MM-dd格式
	 * 
	 * @param date
	 *            时间
	 * 
	 * @return String
	 */
	public static String formatDateDay(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		return sdf.format(date);
	}

	/**
	 * 请求数据并且获得返回值
	 * 
	 * @param requestUrl
	 *            请求链接
	 * 
	 * @param requestData
	 *            请求参数
	 * 
	 * @param method
	 *            请求方式
	 * 
	 * @param charset
	 *            编码
	 * 
	 * @return String
	 * 
	 * @throws IOException
	 */
	public static String readResponse(String requestUrl, String requestData,
			String method, String charset) throws IOException {
		OutputStreamWriter out = null;
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod(method);
			conn.setRequestProperty("Content-Type", "text/html");
			conn.setRequestProperty("Accept-Charset", charset);
			conn.setUseCaches(false);
			conn.setDoOutput(true);
			conn
					.setRequestProperty("Content-Length", ""
							+ requestData.length());
			out = new OutputStreamWriter(conn.getOutputStream(), charset);
			out.write(requestData);
			out.flush();
			out.close();
			// 获取响应状态
			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				System.err.println("connect failed!");
				return "";
			} else {
				// 获取响应内容体
				String line, result = "";
				BufferedReader in = new BufferedReader(new InputStreamReader(
						conn.getInputStream(), charset));
				while ((line = in.readLine()) != null) {
					result += line + "\n";
				}
				return result;
			}
		} catch (SocketException se) {
			se.printStackTrace();
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (out != null)
				out.close();
		}
	}

	public static String readerText(String filePath) throws IOException {
		File file = new File(filePath);
		String sqlText = new String();
		if (file.exists()) {
			InputStreamReader inputStreamReader = new InputStreamReader(
					new FileInputStream(file));
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);
			String str;
			while ((str = bufferedReader.readLine()) != null) {
				sqlText += (str + "\n");
			}
			try {
				bufferedReader.close();
				inputStreamReader.close();
			} catch (Exception excep) {
				excep.printStackTrace();
			}
			return sqlText;
		}
		return null;
	}

	/**
	 * 获取一周列表
	 * 
	 * @return List
	 * 
	 */
	public static List<Map<String, String>> getWeekdayList() {
		String[] weekday = { "周一", "周二", "周三", "周四", "周五", "周六", "周日" };
		List<Map<String, String>> weekdayList = new ArrayList<Map<String, String>>();
		for (int i = 0; i < weekday.length; i++) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("name", weekday[i]);
			map.put("value", String.valueOf(i + 1));
			map.put("checked", "");
			weekdayList.add(map);
		}
		return weekdayList;
	}

	/**
	 * 日期返回星期几
	 * 
	 * @param date
	 * 
	 * @return int
	 */
	public static int dayOfWeek(String date) {
		try {
			Calendar c = Calendar.getInstance();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			c.setTime(dateFormat.parse(date));
			int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
			return dayOfWeek == 0 ? 7 : dayOfWeek;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	/**
	 * 取得当前日期是多少周
	 * 
	 * @param date
	 * @return
	 */
	public static int getWeekOfYear(Date date) {
		Calendar c = new GregorianCalendar();
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.setMinimalDaysInFirstWeek(7);
		c.setTime(date);

		return c.get(Calendar.WEEK_OF_YEAR);
	}

	/**
	 * 得到某年某周的第一天
	 * 
	 * @param year
	 * @param week
	 * @return
	 */
	public static String getFirstDayOfWeek(int year, int week) {
		Calendar c = new GregorianCalendar();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, Calendar.JANUARY);
		c.set(Calendar.DATE, 1);

		Calendar cal = (GregorianCalendar) c.clone();
		cal.add(Calendar.DATE, week * 7);

		return formatDateDay(getFirstDayOfWeek(cal.getTime()));
	}

	/**
	 * 得到某年某周的最后一天
	 * 
	 * @param year
	 * @param week
	 * @return
	 */
	public static String getLastDayOfWeek(int year, int week) {
		Calendar c = new GregorianCalendar();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, Calendar.JANUARY);
		c.set(Calendar.DATE, 1);

		Calendar cal = (GregorianCalendar) c.clone();
		cal.add(Calendar.DATE, week * 7);

		return formatDateDay(getLastDayOfWeek(cal.getTime()));
	}

	/**
	 * 取得当前日期所在周的第一天
	 * 
	 * @param date
	 * @return
	 */
	public static Date getFirstDayOfWeek(Date date) {
		Calendar c = new GregorianCalendar();
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.setTime(date);
		c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
		return c.getTime();
	}

	/**
	 * 取得当前日期所在周的最后一天
	 * 
	 * @param date
	 * @return
	 */
	public static Date getLastDayOfWeek(Date date) {
		Calendar c = new GregorianCalendar();
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.setTime(date);
		c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
		return c.getTime();
	}
	
	
	/**
	 * 当前日期或指定日期加上天数，结果为一个日期 tmpdate 指定日期（yyyyMMdd）或者为空时则取当前日期 iday
	 * 需要加减的天数，如果减则填写负数 sipt 需要使用的分隔符
	 */
	public static String CurrentDate(String tmpdate, int iday, String sipt) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		if (tmpdate.equals("")) {// 如果时间为空，取当前日期
			Date currentTime = new Date();
			SimpleDateFormat smpDateTime = new SimpleDateFormat("yyyyMMdd");
			tmpdate = smpDateTime.format(currentTime);
		}

		Date curdate = sdf.parse(tmpdate, new ParsePosition(0));

		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(curdate);
		rightNow.add(Calendar.DATE, iday);// 你要加减的日期
		Date dt = rightNow.getTime();
		String reStr = sdf.format(dt);
		if (!sipt.equals("")) {
			reStr = reStr.substring(0, 4) + sipt + reStr.substring(4, 6) + sipt
					+ reStr.substring(6, 8);
		}
		return reStr;

	}
	
	/**
	 * 取得系统当前时间
	 * 
	 * @return String yyyy-mm-dd
	 */
	public static String getpardate() {
		Date currentTime = new Date();
		SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd");
		String s = simpledateformat.format(currentTime);
		return s;
	}
	
	/**
	 * 取得系统当前时间
	 * 
	 * @return String yyyymmdd
	 */
	public static String getCurrentDate2() {
		Calendar rightNow = Calendar.getInstance();
		int year = rightNow.get(Calendar.YEAR);
		int month = rightNow.get(Calendar.MONTH) + 1;
		int day = rightNow.get(Calendar.DATE);
		return year + "-" + month + "-" + day;
	}
	
	// 由"yyyy-mm-dd"型串转换为yyyymmdd型

	public static String getNumDate(String strDate) {

		String theDay = null;

		if (strDate != null && strDate.length() > 9) {

			theDay = strDate.substring(0, 4) + strDate.substring(5, 7)
					+ strDate.substring(8, 10);

			return theDay;

		}

		return null;

	}

	/**
	 * 对字符串进行格式化
	 * 
	 * @param str
	 *            需要格式化的字符串
	 * @return
	 */
	public static String formatString(String str) {
		if (str == null)
			return "";
		return str.trim();
	}

	/**
	 * 格式化字符串数组
	 * 
	 * @param strArray
	 *            需要格式化的字符串数组
	 * @return
	 */
	public static String[] formatStringArray(String[] strArray) {
		if (strArray == null || strArray.length == 0)
			return new String[] {};
		for (String string : strArray) {
			string = formatString(string);
		}
		return strArray;
	}
	
	/**
	 * 是否包含数字
	 * @param content
	 * @return
	 */
	public static boolean hasPattern(String content) {
		boolean flag = false;
		Pattern p = Pattern.compile(".*-+.*|.*=+.*");
		Matcher m = p.matcher(content);
		if (m.matches())
			flag = true;
		return flag;

	}
	/**
	 * 比较两个时间大小
	 * @param s1
	 * @param s2
	 * @return 1：s1大 	0:相等	-1：s2大		2：出现错误，可能传入格式错误
	 */
	public static int compare(String s1, String s2) {
		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date d1 = simpleDateFormat.parse(s1);
			Date d2 = simpleDateFormat.parse(s2);
			if (d1.getTime() > d2.getTime()) {
				return 1;
			}else if(d1.getTime() == d2.getTime()){
				return 0;
			}else if(d1.getTime() < d2.getTime()){
				return -1;
			}
		} catch (ParseException e) {
			return 2;
		}
		return 2;
	}
	
	public static String getDirDatePath(){
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
		String date = simpleDateFormat.format(new Date());
		return date;
	}
	
	/**
	 * 当前年份
	 * @return
	 */
	public static String getYear(){
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.YEAR)+"";
	}
}
